package com.foreveross.chameleon.sandbox;

import com.foreveross.chameleon.utils.AesTool;
import com.foreveross.chameleon.utils.IOUtils;

import java.io.IOException;


/**
 * @project: chameleon-android-v3
 * @date: 14-8-27
 * @author: wzq
 * description: TODO
 */
public class FileOutputStream extends java.io.OutputStream {
    private byte[] origin;
    private java.io.FileOutputStream innerStream;

    public FileOutputStream(java.io.File f) throws IOException {
        FileInputStream in = new FileInputStream(f);
        origin = IOUtils.stream2Bytes(in);
        in.close();

        //
        innerStream = new java.io.FileOutputStream(f);
    }

    @Override
    public void write(byte[] bytes) throws IOException {
//        byte[] dst = AesTool.getInstance().encryptBytes(bytes);
        byte[] dst = AesTool.encryptBytes(bytes);
        innerStream.write(dst);
    }

    @Override
    public void write(int oneByte) throws IOException {
        innerStream.write(oneByte);
    }

    // append content to the file
    public void append(String str) throws IOException {
        byte[] two = IOUtils.string2Bytes(str, "utf-8");
        if (origin == null || origin.length == 0) {
            write(two);
            return;
        }
        byte[] combined = new byte[origin.length + two.length];
        System.arraycopy(origin, 0, combined, 0, origin.length);
        System.arraycopy(two, 0, combined, origin.length, two.length);

        //
        write(combined);
    }
}
